package com.datn.DataAccess;
import java.io.IOException;
import java.util.ArrayList;

import com.datn.beans.FavouriteBean;
import com.datn.utils.BitmapUtils;
import com.datn.utils.FileUtils;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.util.Log;
import android.widget.Toast;
public class FavouriteDatabaseAdapter {
	public static final String TAG ="UserDatabaseAdapter";

	public static final String KEY_ID = "IdPlace";
	public static final String KEY_USERNAME = "Username";
	public static final String KEY_NAMEPLACE = "NamePlace";
	public static final String KEY_DESCRIPTION = "Description";
	public static final String KEY_PHONENUMBER = "PhoneNumber";
	public static final String KEY_EMAIL = "EmailPlace";
	public static final String KEY_URL = "URLPlace";
	public static final String KEY_LONGITUDE = "Longitude";
	public static final String KEY_LATITUDE = "Latitude";
	public static final String KEY_IMAGE = "ImagePlacePath";
	public static final String KEY_ADDRESS = "Address";
	public static final String KEY_TYPE = "Type";

	public static final String TYPE_FAVOURITE="FAVOURITE";
	public static final String TYPE_RECENT="RECENT";

	private static final String DATABASE_NAME = "NearLocationDatabase";
	private static final String DATABASE_TABLE = "tblPlace";
	private static final int DATABASE_VERSION = 6;

	private DatabaseHelper mDbHelper;
	private SQLiteDatabase mDB;

	private final Context mContext;



	public FavouriteDatabaseAdapter(Context ctx){
		this.mContext = ctx;
	}

	public FavouriteDatabaseAdapter open()
	{		
		mDbHelper = new DatabaseHelper(mContext, DATABASE_NAME, null, DATABASE_VERSION);
		mDB = mDbHelper.getWritableDatabase();
		return this;
	}

	public void close(){
		mDbHelper.close();
	}

	private Cursor getCursorFavouritePlaceWithUser(String username){
		return mDB.query(DATABASE_TABLE, null, KEY_USERNAME+"=? AND "+KEY_TYPE+"=?", new String[]{username,TYPE_FAVOURITE}, null, null, null);
	}

	private Cursor getCursorRecentPlaceWithUser(String username){
		return mDB.query(DATABASE_TABLE, null, KEY_USERNAME+"=? AND "+KEY_TYPE+"=?", new String[]{username,TYPE_RECENT}, null, null, KEY_ID+" DESC");
	}

	private Cursor getCursorPlaceIdFromLatLng(String lat, String lng){
		return mDB.query(DATABASE_TABLE, null, KEY_LATITUDE+"=? AND "+KEY_LONGITUDE+"=? AND "+KEY_TYPE+"=?", new String[]{lat,lng,TYPE_FAVOURITE}, null, null, null);
	}

	public int getPlaceIdFromLatLng(String lat, String lng){
		Cursor cursor = getCursorPlaceIdFromLatLng(lat, lng);
		if (cursor!=null){
			while (cursor.moveToNext()){
				return cursor.getInt(cursor.getColumnIndexOrThrow(KEY_ID));
			}
		}
		return -1;
	}

	private Cursor getCursorPlaceIdFromLatLngRecent(String lat, String lng){
		return mDB.query(DATABASE_TABLE, null, KEY_LATITUDE+"=? AND "+KEY_LONGITUDE+"=? AND "+KEY_TYPE+"=?", new String[]{lat,lng,TYPE_RECENT}, null, null, null);
	}

	public int getPlaceIdFromLatLngRecent(String lat, String lng){
		Cursor cursor = getCursorPlaceIdFromLatLngRecent(lat, lng);
		if (cursor!=null){
			while (cursor.moveToNext()){
				return cursor.getInt(cursor.getColumnIndexOrThrow(KEY_ID));
			}
		}
		return -1;
	}

	public byte[] getImageFromLatLng(String lat, String lng){
		Cursor cursor = getCursorPlaceIdFromLatLng(lat, lng);
		if (cursor!=null){
			while (cursor.moveToNext()){
				return cursor.getBlob(cursor.getColumnIndexOrThrow(KEY_IMAGE));
			}
		}

		Cursor cursorRecent = getCursorPlaceIdFromLatLngRecent(lat, lng);
		if (cursorRecent!=null){
			while (cursorRecent.moveToNext()){
				return cursorRecent.getBlob(cursor.getColumnIndexOrThrow(KEY_IMAGE));
			}
		}

		return null;
	}


	public ArrayList<FavouriteBean> getFavouritePlaceWithUser(String username){
		Cursor cursor = getCursorFavouritePlaceWithUser(username);
		ArrayList<FavouriteBean> listFavourite=new ArrayList<FavouriteBean>();
		if (cursor!=null){
			while (cursor.moveToNext()){
				FavouriteBean bean=new FavouriteBean();
				bean.setDescription(cursor.getString(cursor.getColumnIndexOrThrow(KEY_DESCRIPTION)));
				bean.setEmail(cursor.getString(cursor.getColumnIndexOrThrow(KEY_EMAIL)));
				bean.setId(cursor.getInt(cursor.getColumnIndexOrThrow(KEY_ID)));
				bean.setLatitude(cursor.getDouble(cursor.getColumnIndexOrThrow(KEY_LATITUDE)));
				bean.setLongitude(cursor.getDouble(cursor.getColumnIndexOrThrow(KEY_LONGITUDE)));
				bean.setNameplace(cursor.getString(cursor.getColumnIndexOrThrow(KEY_NAMEPLACE)));
				bean.setPhonenumber(cursor.getString(cursor.getColumnIndexOrThrow(KEY_PHONENUMBER)));
				bean.setUrl(cursor.getString(cursor.getColumnIndexOrThrow(KEY_URL)));
				bean.setUsername(cursor.getString(cursor.getColumnIndexOrThrow(KEY_USERNAME)));
				bean.setAddress(cursor.getString(cursor.getColumnIndexOrThrow(KEY_ADDRESS)));
				byte[] arrImage=cursor.getBlob(cursor.getColumnIndexOrThrow(KEY_IMAGE));
				if (arrImage!=null){
					if (arrImage.length>0) bean.setImage(BitmapUtils.getBitmapFromByteArray(arrImage));
					else bean.setImage(null);
				}
				else bean.setImage(null);

				listFavourite.add(bean);
			}
		}
		else{
			Toast.makeText(mContext, "Cannot get data from SQLite", Toast.LENGTH_LONG).show();
		}
		return listFavourite;
	}


	public ArrayList<FavouriteBean> getRecentPlaceWithUser(String username){
		Cursor cursor = getCursorRecentPlaceWithUser(username);
		ArrayList<FavouriteBean> listRecent=new ArrayList<FavouriteBean>();
		try{	

			if (cursor!=null){
				while (cursor.moveToNext()){
					FavouriteBean bean=new FavouriteBean();
					//bean.setDescription(cursor.getString(cursor.getColumnIndexOrThrow(KEY_DESCRIPTION)));
					//bean.setEmail(cursor.getString(cursor.getColumnIndexOrThrow(KEY_EMAIL)));
					bean.setId(cursor.getInt(cursor.getColumnIndexOrThrow(KEY_ID)));
					bean.setLatitude(cursor.getDouble(cursor.getColumnIndexOrThrow(KEY_LATITUDE)));
					bean.setLongitude(cursor.getDouble(cursor.getColumnIndexOrThrow(KEY_LONGITUDE)));
					bean.setNameplace(cursor.getString(cursor.getColumnIndexOrThrow(KEY_NAMEPLACE)));
					bean.setPhonenumber(cursor.getString(cursor.getColumnIndexOrThrow(KEY_PHONENUMBER)));
					bean.setUrl(cursor.getString(cursor.getColumnIndexOrThrow(KEY_URL)));
					bean.setUsername(cursor.getString(cursor.getColumnIndexOrThrow(KEY_USERNAME)));
					bean.setAddress(cursor.getString(cursor.getColumnIndexOrThrow(KEY_ADDRESS)));
					//				byte[] arrImage=cursor.getBlob(cursor.getColumnIndexOrThrow(KEY_IMAGE));
					//				if (arrImage!=null){
					//					if (arrImage.length>0) bean.setImage(BitmapUtils.getBitmapFromByteArray(arrImage));
					//					else bean.setImage(null);
					//				}
					//				else bean.setImage(null);

					listRecent.add(bean);
				}
			}
			else{
				Toast.makeText(mContext, "Cannot get data from SQLite", Toast.LENGTH_LONG).show();
			}
		}
		catch(Exception ex){
			Toast.makeText(mContext, "Cannot get data from SQLite", Toast.LENGTH_LONG).show();
		}
		return listRecent;
	}

	public long createFavourite(FavouriteBean bean){
		if (bean==null) return -1;
		ContentValues inititalValues = new ContentValues();		
		try {
			if (!isExistFavourite(bean.getLatitude(), bean.getLongitude())){		
				inititalValues.put(KEY_DESCRIPTION, bean.getDescription());
				inititalValues.put(KEY_EMAIL, bean.getEmail());
				//inititalValues.put(KEY_ID, bean.getId());
				inititalValues.put(KEY_LATITUDE, bean.getLatitude());
				inititalValues.put(KEY_LONGITUDE, bean.getLongitude());
				inititalValues.put(KEY_NAMEPLACE, bean.getNameplace());
				inititalValues.put(KEY_PHONENUMBER, bean.getPhonenumber());
				inititalValues.put(KEY_URL, bean.getUrl());
				inititalValues.put(KEY_USERNAME, bean.getUsername());
				inititalValues.put(KEY_ADDRESS, bean.getAddress());
				inititalValues.put(KEY_IMAGE, BitmapUtils.getByteArrayFromBitmap(bean.getImage()));
				inititalValues.put(KEY_TYPE, TYPE_FAVOURITE);
				return mDB.insert(DATABASE_TABLE, null, inititalValues);
			}
		} catch (Exception e) {
			// TODO: handle exception
			Toast.makeText(mContext, "Error when create Favourite" , Toast.LENGTH_LONG).show();
		}

		return -1;		
	}

	private Cursor getCursorFavouriteLastest(String username){
		return mDB.query(DATABASE_TABLE, null, KEY_TYPE+"=?", new String[]{TYPE_FAVOURITE}, null, null, null);
	}

	public int getLastestFavourite(String username){
		Cursor cursor = getCursorFavouriteLastest(username);
		int id_place_lastest = -1;
		if (cursor!=null){
			while (cursor.moveToNext()){
				id_place_lastest = cursor.getInt(cursor.getColumnIndexOrThrow(KEY_ID));
				break;
			}
		}
		return id_place_lastest;
	}

	public long createRecent(FavouriteBean bean){
		if (bean==null) return -1;
		ContentValues inititalValues = new ContentValues();		
		if (!isExistRecent(bean.getLatitude(), bean.getLongitude())){		
			/*inititalValues.put(KEY_DESCRIPTION, bean.getDescription());
			inititalValues.put(KEY_EMAIL, bean.getEmail());*/
			inititalValues.put(KEY_LATITUDE, bean.getLatitude());
			inititalValues.put(KEY_LONGITUDE, bean.getLongitude());
			inititalValues.put(KEY_NAMEPLACE, bean.getNameplace());
			inititalValues.put(KEY_PHONENUMBER, bean.getPhonenumber());
			inititalValues.put(KEY_URL, bean.getUrl());
			inititalValues.put(KEY_USERNAME, bean.getUsername());
			inititalValues.put(KEY_ADDRESS, bean.getAddress());
			byte[] imagebyte = null; 
			if (bean.getImage()!=null){
				imagebyte = BitmapUtils.getByteArrayFromBitmap(bean.getImage());
			}

			if (imagebyte!=null){
				if (imagebyte.length>0){
					inititalValues.put(KEY_IMAGE, imagebyte);
				}
			}

			inititalValues.put(KEY_TYPE, TYPE_RECENT);
			return mDB.insert(DATABASE_TABLE, null, inititalValues);
		}
		return -1;		
	}


	public int deleteRecentPlace(FavouriteBean bean){
		return mDB.delete(DATABASE_TABLE, KEY_ID+"=?", new String[]{String.valueOf(bean.getId())});
	}

	public int deleteFavouritePlace(FavouriteBean bean){
		return mDB.delete(DATABASE_TABLE, KEY_ID+"=?", new String[]{String.valueOf(bean.getId())});
	}

	public int updateRecentPlace(FavouriteBean bean){
		int result = -1;
		try{
			if (bean!=null){
				if (isExistRecent(bean.getLatitude(), bean.getLongitude())){
					Log.v("Update recent place", "Is exist recent place --> Deleting");
					result = deleteRecentPlace(bean);
					Log.v("Update recent place", "Is exist recent place --> COMPLETED");
				}
				result = (int)createRecent(bean);
				Log.v("Update recent place", "Create recent success");
			}
		}
		catch(Exception ex){
			Toast.makeText(mContext, "Update Recent failed", Toast.LENGTH_LONG).show();
		}
		return result;
	}


	private boolean isExistFavourite(double latitude, double longitude){
		Cursor cursor =  mDB.query(DATABASE_TABLE, new String[]{KEY_LATITUDE, KEY_LONGITUDE, KEY_TYPE}, KEY_LATITUDE+"=? AND "+KEY_LONGITUDE+"=? AND "+KEY_TYPE+"=?", new String[]{String.valueOf(latitude), String.valueOf(longitude), TYPE_FAVOURITE}, null, null, null);
		return (cursor.getCount()>0);
	}

	private boolean isExistRecent(double latitude, double longitude){
		Cursor cursor =  mDB.query(DATABASE_TABLE, new String[]{KEY_LATITUDE, KEY_LONGITUDE, KEY_TYPE}, KEY_LATITUDE+"=? AND "+KEY_LONGITUDE+"=? AND "+KEY_TYPE+"=?", new String[]{String.valueOf(latitude), String.valueOf(longitude), TYPE_RECENT}, null, null, null);
		return (cursor.getCount()>0);
	}






	/*public long createUser(String name, String password, String email){
		ContentValues inititalValues = new ContentValues();
			inititalValues.put(KEY_USERNAME, name);
			inititalValues.put(KEY_PASSWORD, password);
			inititalValues.put(KEY_EMAIL, email);
			inititalValues.put(KEY_ROLE, 1);
		return mDB.insert(DATABASE_TABLE, null, inititalValues);
	}

	public boolean isExistUser(String username){
		if ((username==null)||(username.trim().isEmpty())) return false;
		Cursor cursor =  mDB.query(DATABASE_TABLE, new String[]{KEY_USERNAME}, KEY_USERNAME+"=?", new String[]{username}, null, null, null);
		return (cursor.getCount()>0);
	}

	public boolean isExistEmail(String stEmail){
		if ((stEmail==null)||(stEmail.trim().isEmpty())) return false;
		Cursor cursor =  mDB.query(DATABASE_TABLE, new String[]{KEY_EMAIL}, KEY_EMAIL+"=?", new String[]{stEmail}, null, null, null);
		return (cursor.getCount()>0);
	}

	public boolean isUser(String username, String password){
		if ((username==null)||(password==null)) return false;
		if ((username.equalsIgnoreCase(""))||(password.equalsIgnoreCase(""))) return false;
		Cursor cursor =  mDB.query(DATABASE_TABLE, new String[]{KEY_USERNAME, KEY_PASSWORD}, KEY_USERNAME+"=? AND "+KEY_PASSWORD+"=?", new String[]{username,password}, null, null, null);
		return (cursor.getCount()>0);
	}*/



}
